package org.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import org.example.entity.AliPay;
import org.example.entity.Order;
import org.example.entity.OrderVO;
import org.example.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderHandler {

    @Autowired
    private OrderRepository orderRepository;


    @GetMapping("/pay/{tradeNo}/{subject}/{totalAmount}") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public String pay(@PathVariable("tradeNo") String tradeNo, @PathVariable("subject") String subject, @PathVariable("totalAmount") String totalAmount, HttpServletResponse httpResponse) throws Exception {
//
//

        //orderRepository.updateStatus2(Long.valueOf(tradeNo));

        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsmW4SRMTFESuNbWOFf7demydAs7AMK8LY+uvVXISrcL2zRw2CySEGUJkU7kQeEVqe4RnPCQ5qOCb6bliZc0Cha9nOyzqmJyjDTuJH1tuiFk3vwatWFXNN2XBaMmz6hBp+uFPtEZdqyEhKSl9ccqv5cEuvrcNEkeCV5kdjZ3HDS8pyftdHRAx5rxER1LD1XsSwKGyX4kTpYbBLz/LkqGd2hDvmvVACKu2yuSQMztZsX27+oy6X0Db1Xgh4GTMS0U30jQrZpl0aOJhjwEas9VO/5RXO3h6q+gTB20kY7xmX9KZWLszZO84SYBhCOCApj4F3nk5qaZBoOU2tFddifps9AgMBAAECggEADc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EWzgK9zWPp6oDjM42a4eov4rVq5jpnNMfY1zM5hZKDbOKONt2dxjE5c/ZBFPbmT5kRoFIe3MYzDk69N9bJ9gV1gLE35af45dKsKM0sEMcnoDTlXAfxu24NETuEWwUzoU=";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiucmiW6tc9IV4C/g6665YPdNXo4r5qNic2kxEoc2NS9TR8eXUqTmOwZWECudIRmCS/z7/Som1qLjcsUahP/i8B8f/pc1ZncETrBok/qupU9o8HVtYYqaGnmxTpYgcZ4zUj4nKRvWdQIJoIos8FoUk8A1MoYOxwYVCFoFssrEN8w8sGxPorejXTfQdBMYWcNQNOveOQASLJPoEgBWsDU70L0YHeLz5dtim3JUyMku7h9PygoKBV5A6ZReQBZ5FbiefN2qZNOBKXg4le9v8vdJn+ulaH3QaPw8f3v4YKu/rt4e6MuKAkyq8AgajAszpNRsBGm48eClXLOCrXPvkhX17QIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
      //  https://openapi-sandbox.dl.alipaydev.com/gateway.do
        alipayConfig.setAppId("9021000149686287");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        request.setReturnUrl("http://localhost:8030/menu/redirect/person_order");
        request.setNotifyUrl("http://dbd6c85e.natappfree.cc/order/notify");

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(tradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject("order payment");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        request.setBizModel(model);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;

//        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,
//                "9021000149686287",
//                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsmW4SRMTFESuNbWOFf7demydAs7AMK8LY+uvVXISrcL2zRw2CySEGUJkU7kQeEVqe4RnPCQ5qOCb6bliZc0Cha9nOyzqmJyjDTuJH1tuiFk3vwatWFXNN2XBaMmz6hBp+uFPtEZdqyEhKSl9ccqv5cEuvrcNEkeCV5kdjZ3HDS8pyftdHRAx5rxER1LD1XsSwKGyX4kTpYbBLz/LkqGd2hDvmvVACKu2yuSQMztZsX27+oy6X0Db1Xgh4GTMS0U30jQrZpl0aOJhjwEas9VO/5RXO3h6q+gTB20kY7xmX9KZWLszZO84SYBhCOCApj4F3nk5qaZBoOU2tFddifps9AgMBAAECggEADcVsJ97+yC53iCA7OZKYId9FQX9Uw5PWRxO2L17jYv5q1FwN8upzTRqvLCFao/+EeHrDYWZ6lPUH/yFAxnWQqZB+X2aNtmYXdYXcvhihi4w2CbQtJIAvo/1+XmP5l/9kUcoJQDgQGcADLJJEi47Gs+9GyqyVkOoGvk8SURcW15sZs/6E6rQuPrPKZJirYVwh9wGKFuPDh/MVUlFRgZgW7eXX1cu6XKFYkKdbfgK5XnFe5eCv0aC01fTursizKTABLveoRMkmskBQ0o4xjf29daReUvKO7rV3STne8ENdnQ8dj3fhxkab7jILuF6yZTByB4zjmKwJdPP0dpjlvzgLjQKBgQDsi2MbpVt15jAJiSLQUIcWhAMMV8sDUC1sgU8gMPw2h5qi8V3pY3oTZVIN/9cXOrJ0s2j31Crjtz6idxMwbxNiTovFbL384OD6hjZeXUuTq1eTIrhg1nlWyHoDh0Gxfb20CB3EX5W7d9+VyAmZX3MPdOhDlMD086dxenu7LgrFTwKBgQC6y6HVIOZvwia0e5Iz9/KXWfIc0IX6YQUB39FE7K3hCOuRoevNziUqsON7CE5iKoplmNiCVu8U75sVVeW/9vZAsH1eFBPstobO7WZ06KQ+txnTMUTu+HeS3duodQWu+O/H1HuaKmqUNEeG6X3AaxeJ830+gapD9+c42P3egy/LswKBgQCkIlgj38ql9ZLRmxHIIIiMDBAdaXHaG7FZQCTKfpMTt2aKuBblEnyrpruYMTVrzfP0XGVyygr0tbtFeoCbNAfsR/pehIUUSmpyC9z//5aoodUDqKztrQTHPhbECf+AjHKs0JDvKTA5xAUl5ocaoIuzZvifpEF79vHyIP5oNJuOqwKBgCH1JuRh6MJkXzjsRfXgm19cYKFQXyrXPFvM3nRTOoDwaDK/ZuixExyhr5kMN4OtDB/QG3wGZcw+isjkJrIxKS81ZnUV3VFpFTTE/509Na6ZBr7X9BolXUd7wZTsQS4/3wdK33V1RI7QujgSdmPmlA7mDtywIc3dYVF6URyEaMn1AoGAHC/ZHBlyNbJCVMJ8OwEm5j0/Jmav95gUWtynziqZdobEWzgK9zWPp6oDjM42a4eov4rVq5jpnNMfY1zM5hZKDbOKONt2dxjE5c/ZBFPbmT5kRoFIe3MYzDk69N9bJ9gV1gLE35af45dKsKM0sEMcnoDTlXAfxu24NETuEWwUzoU=", "json",
//                "UTF-8",
//                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiucmiW6tc9IV4C/g6665YPdNXo4r5qNic2kxEoc2NS9TR8eXUqTmOwZWECudIRmCS/z7/Som1qLjcsUahP/i8B8f/pc1ZncETrBok/qupU9o8HVtYYqaGnmxTpYgcZ4zUj4nKRvWdQIJoIos8FoUk8A1MoYOxwYVCFoFssrEN8w8sGxPorejXTfQdBMYWcNQNOveOQASLJPoEgBWsDU70L0YHeLz5dtim3JUyMku7h9PygoKBV5A6ZReQBZ5FbiefN2qZNOBKXg4le9v8vdJn+ulaH3QaPw8f3v4YKu/rt4e6MuKAkyq8AgajAszpNRsBGm48eClXLOCrXPvkhX17QIDAQAB",
//                "RSA2");
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        alipayRequest.setReturnUrl("http://r27d86b4.natappfree.cc/alipay/return");
//        alipayRequest.setNotifyUrl("http://r27d86b4.natappfree.cc/alipay/notify");
//        alipayRequest.setBizContent("{" + "    \"out_trade_no\":\"" + tradeNo
//                + "\"," + "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + "    \"total_amount\":\"" +totalAmount + "\"," + "    \"subject\":\"订单支付\"}");
//        String form = "";
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody();
//        } catch (AlipayApiException e) {
//
//        }
//        return  form;
//        response.setContentType("text/html;charset=UTF-8");
//        response.getWriter().write(form);
//        response.getWriter().flush();

//
//        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
//                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
//        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
//
//        AliPay aliPay = new AliPay();
//        aliPay.setTraceNo(tradeNo);
//        aliPay.setSubject(subject);
//        aliPay.setTotalAmount(Double.parseDouble(totalAmount));
//
//        request.setBizContent("{" + "    \"out_trade_no\":\"" + tradeNo
//                 + "\"," + "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + "    \"total_amount\":\"" + totalAmount
//                + "\"," + "    \"subject\":\"订单支付\"}");
//
//        String form = "";
//        try {
//            // 调用SDK生成表单
//            form = alipayClient.pageExecute(request).getBody();
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        // 直接将完整的表单html输出到页面
//        return form;
    }

    public static Map<String, Object> getH5PaymentParams(AliPay order){
        Map<String, Object> bizContent = new HashMap<>();
        bizContent.put("out_trade_no", order.getTraceNo());
        bizContent.put("total_amount", order.getTotalAmount());
        bizContent.put("subject", order.getSubject());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        return bizContent;
    }


    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 更新订单未已支付
            Order order = new Order();
            orderRepository.updateStatus2(Long.valueOf(tradeNo));
        }
        return "success";
    }

    @PostMapping("/save")
    public void save (@RequestBody Order order) {
        order.setDate(new Date());
        order.setState(2);
        orderRepository.save(order);
    }

    @GetMapping("/findAllByUid/{index}/{limit}/{uid}")
    public OrderVO findAllByUid (@PathVariable("index") int index, @PathVariable("limit") int limit, @PathVariable("uid") long uid) {
        OrderVO orderVO = new OrderVO();
        orderVO.setMsg("");
        orderVO.setCount(orderRepository.countByUid(uid));
        orderVO.setData(orderRepository.findAllByUid(index, limit, uid));
        return orderVO;
    }

    @GetMapping("/findAll/{index}/{limit}")
    public OrderVO findAll(@PathVariable("index")int index, @PathVariable("limit")int limit) {
        OrderVO orderVO = new OrderVO();
        orderVO.setMsg("");
        orderVO.setCount(orderRepository.count());

        List<Order> all = orderRepository.findAll(index, limit);
        all.forEach(ele-> {
            ele.setUser(orderRepository.findUserById(ele.getUid()));
        });

        orderVO.setData(all);
        return orderVO;
    }

    @PutMapping("/updateState/{id}")
    public void update(@PathVariable("id") long id) {
        orderRepository.updateStatus(id);
    }

}